package com.example.web.task;

import java.util.Date;

import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

/**
 * 	在不重启服务的前提下，动态设置定时周期
 * @author yzl
 *
 */
@Slf4j
@Component
@EnableScheduling
public class ScheduledTask2 implements SchedulingConfigurer{

	//定时器定时周期
    private static String cron;

    //线程轮询数据休眠时间
    private static long sleepTime;

    public ScheduledTask2() {
        //初始化定时周期
        cron = "0/5 * * * * ?";

        //初始化休眠时间
        String sleepTimeString = "500";

        sleepTime = Long.valueOf(sleepTimeString);
        //开启监听线程,监听cron在数据库的变化
        new Thread(new Runnable() {
            @Override
            public void run() {
                while(true) {
                    try {
                        //每隔多长时间查询一次数据库,判断是否发生变化,10秒
                        Thread.sleep(sleepTime);
                    } catch (InterruptedException e) {
                       log.error("taskThread error",e);
                    }
                    //从数据库获取最新任务值
                    String latestCron = "0/5 * * * * ?";
                    if (!latestCron.equals(cron)) {
                        //修改
                        cron = latestCron;
                    }
                }
            }
        }).start();
    }

	@Override
	public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
		Runnable task = new Runnable() {
            @Override
            public void run() {
                try {
                    //业务代码
                	System.out.println("ScheduledTask2 +++ 执行定时任务时间:"+new Date());
                }catch(Exception e){
                    log.error("error",e);
                }
            }
        };

        Trigger trigger = new Trigger() {
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext) {
                //任务触发，可修改任务的执行周期.
                CronTrigger trigger = new CronTrigger(cron);
                Date nextExec = trigger.nextExecutionTime(triggerContext);
                return nextExec;
            }
        };

        taskRegistrar.addTriggerTask(task, trigger);
	}
}
